<?php
class Core_Form_Xml
{
	/* @var $_form Zend_Form */
	private static $_form;
	
	public static function loadForm($xml)
	{
		self::$_form = new Zend_Form();
		self::_processFormXml($xml);
		return self::$_form;
		
	}
	
	private static function _processFormXml($xml)
	{
		$json = new Zend_Json();
		$formArray = json_decode($json->fromXml($xml,false),true);
		foreach ($formArray['form']['element'] as $formElement) {
			self::_createElement($formElement);
		}
	} 
	
	private static function _createElement($elementArray)
	{
		/* @var $element Zend_Form_Element */
		$element = self::$_form->createElement($elementArray['@attributes']['type'], $elementArray['@attributes']['name']);
		
		if (array_key_exists("required", $elementArray)) {
			$element->setRequired($elementArray['required']);
		}
		if (array_key_exists("attribs", $elementArray)) {
			$element->setAttribs(json_decode($elementArray['attribs'],true));
		}
		if (array_key_exists("validator", $elementArray)) {
			$element->addValidator($elementArray['validator']['@attributes']['name'], false, json_decode($elementArray['validator']['options'],true));
		}
		if (array_key_exists("errorMessage", $elementArray)) {
			$element->addErrorMessage($elementArray['errorMessage']);
		}
		if (array_key_exists("label", $elementArray)) {
			$element->setLabel($elementArray['label']);
		}
		
		self::$_form->addElement($element);
	}
}